<template>
  <n-grid :x-gap="12" :y-gap="8" responsive="screen" item-responsive>
    <n-gi span="12 m:8 l:6 xl:4" 
      v-for="item,index in clients" :key="'client_' + index">
        <n-card class="client-card">
            <template #header>
              <span class="shadow-click" @click="showForm(true, item)">{{item.name}}</span>
            </template>
            <div class="address"> {{ item.host }}:{{ item.port }}</div>
            
            <n-scrollbar style="max-height:10em" :trigger="'hover'" v-if="item.deviceInfo">
              <div class="spaces">
                <span v-for="di,index in item.deviceInfo" :key="'deviceInfo_'+index">  
                  {{ di.name }} &nbsp;
                  (<span class="unuse">{{di.usableSpaceStr}}</span> / <span class="total">{{di.totalSpaceStr}}</span>)
                  <br/>
                </span>
              </div>
            </n-scrollbar>
        </n-card>
    </n-gi>
  </n-grid>

  <!-- 添加和编辑弹窗 -->
  <n-modal
    v-model:show="showModal"
    class=""
    preset="dialog"
    :title="isUpdate ? '···': '...'"
    :bordered="false"
    :segmented="{content: 'soft', footer: 'soft'}"
    :show-icon="false"
    :maskClosable="false"
    :style="{ width: '40em' }"
    >

    <n-form     
      label-placement="left"
      label-width="7em"
      ref="formRef" :model="formData" :rules="rules"
      >
      <n-form-item path="name" label="名称">
        <n-input v-model:value="formData.name" placeholder="名称" />
      </n-form-item>
      <!---->
      <n-form-item path="protocol" label="协议" v-if="isUpdate">
        <n-input v-model:value="formData.protocol" placeholder="协议" />
      </n-form-item>
      <n-form-item path="host" label="IP或域名">
        <n-input v-model:value="formData.host" placeholder="IP或域名" />
      </n-form-item>
      <n-form-item path="port" label="端口">
        <n-input v-model:value="formData.port" placeholder="端口" />
      </n-form-item>


      <div style="display: flex; justify-content: flex-end">
        <n-button round type="error" style="margin-right:4px" v-if="isUpdate"
          @click="handleDelete()" :loading="formLoading">
          删除
        </n-button>
        <n-button round type="primary" style="margin-right:4px"
          @click="handleSubmit()" :loading="formLoading">
          {{ isUpdate ? '更新' : '保存' }}
        </n-button>

        <n-button round type="" @click="showModal=false" >
          关闭
        </n-button>
      </div>
    </n-form>
  </n-modal>
</template>

<script setup>
import { inject, onMounted, ref } from 'vue'
import serverApi from '/src/api/fsync/server.js'

const clients = ref([])

const showModal = ref(false)
const formRef = ref(null) // 表单组件
const isUpdate = ref(false) // 表单是更新
const formData = ref({}) // 表单数据
const rules = ref({
  name: [ { required: true, message: 'name required', trigger: 'blur' } ],
  host: [ { required: true, message: 'host required', trigger: 'blur' } ],
  port: [ { required: true, message: 'port required', trigger: 'blur' } ],
})
const formLoading = ref(false)

const Message = inject("Message")
const Dialog = inject("Dialog")

const initClient = (client) => {
  // return  {id: 2, name: '前', protocol: 'http',  host: 'localhost', port: '8052', deviceInfo: [] }
  return  { 
    id: client?.id || null,
    name: client?.name || null,
    protocol: client?.protocol || 'http',
    host: client?.host || null,
    port: client?.port || "8052",
  }
}
// 所有 clients
const listClients = async () => {
  await serverApi.clientList().then(res => {
    //console.log("list-client-res", res)
    clients.value = res.data
  })
}

const testClients = () => {
  clients.value.push({id: 1, name: '漳',  protocol: 'http', host: 'localhost', port: '22', deviceInfo: [] })
  clients.value.push({id: 2, name: '前', protocol: 'http',  host: 'localhost', port: '8052', deviceInfo: [] })
  clients.value.push({id: 3, name: '结果', protocol: 'http', host: 'localhost', port: '8052', deviceInfo: [] })
  clients.value.push({id: 4, name: '金良', protocol: 'http', host: 'localhost', port: '8052', deviceInfo: [] })
  clients.value.push({id: 5, name: '沃锁', protocol: 'http', host: 'localhost', port: '8052', deviceInfo: [] })
  clients.value.push({id: 6, name: '视界', protocol: 'http', host: 'localhost', port: '8052', deviceInfo: [] })
}

// showForm(false, vo)  showForm(true, null) 
const showForm = (isUpdateOrNot, client) => {
  showModal.value = true
  isUpdate.value = isUpdateOrNot
  formData.value = initClient(client)
}
// 提交表单
const handleSubmit = async () => {
  formRef.value.validate((errors) => {
    if(errors) {
      console.error(errors)
      return
    }

  // 更新或添加
  let reqMethod = isUpdate.value ? serverApi.clientUpdate : serverApi.clientConnect
  formLoading.value = true
  reqMethod(formData.value).then(res => {
      // console.log("add-client-res", res)
      formLoading.value = false
      closeModal()
      listClients()
    }, err => {
      formLoading.value = false
      Message.error( err.message, { closable: true, duration: 3000 } )
      console.error(err)
    })
  })

}

// 删除
const handleDelete = async () => {
  Dialog.warning({
    title: '删除',
    content: '确认要删除这个 Client ？',
    positiveText: '删除',
    negativeText: '取消',
    maskClosable: false,
    onPositiveClick: () => {
      serverApi.clientDelete(formData.value.id).then(res => {
        closeModal()
        listClients()
      }, err => {
        formLoading.value = false
        Message.error( err.message, { closable: true, duration: 3000 } )
        console.error(err)
      })
    },
  })
}


const showAdd = () => {
  showForm(false, null)
}
const closeModal = () => {
  showModal.value = false
  // isUpdate.value = isUpdateOrNot
  formData.value = initClient()
}

//testClients()
onMounted(() => {
  listClients()
})

defineExpose({
  showAdd,
})

</script>

<style scoped lang="scss">
.client-card{
  position: relative;
}
.address {
  color: #808080;
}
.spaces{
  .unuse{
    color: #36a136;
  }
  .total{
    color: #0a6eab;
  }
}
</style>
